<template>
  <div class="login">
    <!-- 1. 关闭图标 -->
    <span class="close-btn" @click="$router.back()">
      <i class="iconicon-test iconfont"></i>
    </span>
    <!-- 2. Logo 图标 -->
    <h2 class="logo">
      <i class="iconnew iconfont"></i>
    </h2>
    <!-- 3. 输入框 -->
    <MyInput
      placeholder="手机号码"
      msg="手机号输入不合法"
      :rules="rules.username"
      v-model="user.username"
    ></MyInput>
    <MyInput
      placeholder="昵称"
      msg="昵称2-10位"
      :rules="rules.nickname"
      v-model="user.nickname"
    ></MyInput>
    <MyInput
      placeholder="密码"
      type="password"
      msg="密码为3-18位"
      :rules="rules.password"
      v-model="user.password"
    ></MyInput>
    <!-- 4. 一个注册提示 -->
    <div class="tips">
      没有账号？<router-link to="/login" class="red">去登录</router-link>
    </div>
    <!-- 5. 登录按钮 -->
    <MyButton type="primary" @click="registerFn"> 注册 </MyButton>
  </div>
</template>

<script>
// 自定义组件使用步骤：  新建/导入/注册/使用
import MyButton from "../components/MyButton.vue";
import MyInput from "../components/MyInput.vue";
import { userRegisterAPI } from "../apis/user";
export default {
  data() {
    return {
      user: {
        username: "",
        password: "",
        nickname: "",
      },
      rules: {
        username: /^1\d{10}$/,
        password: /^[a-zA-Z0-9~!@#$%^&*()_+=]{3,18}$/,
        nickname: /^.{2,10}$/,
      },
    };
  },
  methods: {
    registerFn() {
      if (
        this.rules.username.test(this.user.username) &&
        this.rules.nickname.test(this.user.nickname) &&
        this.rules.password.test(this.user.password)
      ) {
        userRegisterAPI(this.user).then((res) => {
          // console.log(res);
          // 解构出后端返回的提示信息
          const { message } = res.data;
          if (message === "注册成功") {
            // 成功调用请提示的 success() 方法，图标会有变化
            this.$toast({
              type: "scccess",
              // 支持通过\n换行
              message: "注册成功\n欢迎回来",
              // 关闭时的回调函数
              onClose: () => {
                // 通过 JS 方式跳转到登录页面(编程式导航)
                this.$router.push({ path: "/login" });
              },
            });
          } else {
            // 成功调用轻提示的 fail() 方法，图标会有变化
            this.$toast.fail(message);
          }
        });
      } else {
        this.$toast("输入数据有误");
      }
    },
  },
  components: {
    MyButton,
    MyInput,
  },
};
</script>

<style lang="less" scoped>
.close-btn {
  position: fixed;
  left: 20px;
  top: 20px;
  .iconfont {
    font-size: 20px;
    color: #666;
  }
}
.logo {
  display: flex;
  justify-content: center;
  padding: 60px 0 20px;
  .iconfont {
    color: #d81e06;
    font-size: 120px;
  }
}
.tips {
  padding: 0 30px;
  text-align: right;
}
.red {
  color: #00aa00;
}
</style>